#include "stdafx.h"
#include "thread/errorhandler.hpp"
#include "designpattern/singletonholder.hpp"
using namespace JHCPP::designpattern;

namespace JHCPP
{
	namespace thread
	{
		CErrorHandler* CErrorHandler::m_pHandler = CErrorHandler::defaultHandler();
		CMutex CErrorHandler::m_mutex;

		CErrorHandler::CErrorHandler()
		{
		}

		CErrorHandler::~CErrorHandler()
		{
		}

		void CErrorHandler::exception(const CException& exc)
		{
			jh_debugger_msg(exc.what());
		}

		void CErrorHandler::exception(const std::exception& exc)
		{
			jh_debugger_msg(exc.what());
		}

		void CErrorHandler::exception()
		{
			jh_debugger_msg("unknown exception");
		}

		void CErrorHandler::handle(const CException& exc)
		{
			CMutex::ScopedLock lock(m_mutex);
			try
			{
				m_pHandler->exception(exc);
			}
			catch (...)
			{
			}
		}

		void CErrorHandler::handle(const std::exception& exc)
		{
			CMutex::ScopedLock lock(m_mutex);
			try
			{
				m_pHandler->exception(exc);
			}
			catch (...)
			{
			}
		}

		void CErrorHandler::handle()
		{
			CMutex::ScopedLock lock(m_mutex);
			try
			{
				m_pHandler->exception();
			}
			catch (...)
			{
			}
		}

		CErrorHandler* CErrorHandler::set(CErrorHandler* pHandler)
		{
			jh_check_ptr(pHandler);

			CMutex::ScopedLock lock(m_mutex);
			CErrorHandler* pOld = m_pHandler;
			m_pHandler = pHandler;
			return pOld;
		}

		CErrorHandler* CErrorHandler::get()
		{
			return m_pHandler;
		}

		CErrorHandler* CErrorHandler::defaultHandler()
		{
			static TSingletonHolder<CErrorHandler> sh;
			return sh.get();
		}

	}//end of namespace thread
}//end of namespace JHCPP
